<template>
  <section>
    <el-row v-loading="loading">
      <el-table :data="examineList">
        <el-table-column type="index" label="序号">
        </el-table-column>
        <el-table-column prop="name" label="体检标题">
        </el-table-column>
        <el-table-column label="当前状态">
          <template slot-scope="scope">
            <span v-if="scope.row.state === 2">待生成报告</span>
            <span v-if="scope.row.state === 3">报告生成中</span>
            <span v-if="scope.row.state === 4">已生成报告</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click='computerFraction(scope.row)' size="small">结算分数</el-button>
            <el-button @click='createReportBtn(scope.row)' size="small">生成报告</el-button>
            <el-button @click='editReportBtn(scope.row)' size="small" v-if="scope.row.state === 3">编辑报告</el-button>
            <el-button @click='lookThroughReport(scope)' size="small" v-if="scope.row.state === 4">查看报告</el-button>
            <!--<el-popover placement="top" width="400" trigger="hover">-->
              <!--<img :src="scope.row.signature"/>-->
              <!--<el-row slot="reference"><img :src="scope.row.signature" width="100px"/></el-row>-->
            <!--</el-popover>-->
            <el-button @click='lookThroughFraction(scope.row)' size="small" type="text">查看分数</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-show="totalPage>0" style="margin-top:10px;" small layout="prev, pager, next" :page-count="totalPage" @current-change="goPage"> </el-pagination>
      <el-dialog  :visible.sync="showDialog" v-if="moduleList">
        <el-checkbox-group v-model="selModules">
          <el-checkbox style="width: 25%;margin: 5px 0;" v-for="module in moduleList" :label="module.id" :key="module.id">
            {{module.id}}{{module.title}}
          </el-checkbox>
        </el-checkbox-group>
        <el-button @click="confirmCreateBtn" size="mini" type="primary">确认生成</el-button>
      </el-dialog>
    </el-row>
  </section>
</template>

<script>
  import DateFormat from '@/common/date-formater'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import Vue from 'vue'//后续添加属性，需要vue联动
  import errHandler from '@/assets/errHandler.js'
  export default {
    name: "examineOfFinish",
    data() {
      return {
        examineList:[],
        loading:false,
        totalPage:0,
        showTest:false,
        selModules:[],
        moduleList:null,
        showDialog:false,
        currExamine:null,
        currUser:null,
        tacticsList:[]
      }
    },
    created(){
      this.loading=true
      //获取所有体检
      this.getExamineList()
    },
    watch:{
    },
    computed:{
      ...mapGetters(['department']),
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      goPage(val){//答卷页面翻页
        this.getExamineList(val-1)
      },
      getExamineList(pageNo){
        this.fetch({name:"getExamineList",data:{page:pageNo?pageNo:0}})
          .then(res=>{
            console.log(res.content)
            this.examineList=res.content
            this.totalPage = res.totalPages
            this.loading=false
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getUser(uid){
        this.fetch({name:"getUser",data:{uid}})
          .then(res=>{
            this.currUser=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeBox(res){
        let array=[]
        res.forEach(t=>{
          let tmp={id:t.id,name:t.name,point:0}
          array.push(tmp)
          if(t.childrens){
            tmp.childrens=this.makeBox(t.childrens)
          }
        })
        return array
      },
      fillIn(tacticsArray,res){
        for(let i=0;i<res.length;i++){
          let tmp=res[i]
          if(tmp.childrens){
            this.fillIn(tacticsArray,tmp.childrens)
            tmp.childrens.forEach(c=>{
              tmp.point +=c.point
            })
          }
          for(let j=0;j<tacticsArray.length;j++){
            let tmp2=tacticsArray[j]
            if(tmp2.id === tmp.id){
              tmp.point += parseInt(tmp2.point)
              break
            }
          }
        }
      },
      getTactics(row){//加载策略列表，含子目录
        this.fetch({name:"getTacticsList"})
          .then(res=>{
            let newRes=this.makeBox(res)
            // console.log(newRes)
            this.fillIn(row.data.sum,newRes)
            row.data.sum=newRes
            this.updateExamine(row)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      computerFraction(row){
        console.log(row)
        for(let i=0;i<row.examineItems.length;i++){
          let item =row.examineItems[i]
          if(item.data.answerId){
            //获取答卷
            this.getAnswer(item,item.data.answerId)
          }
        }
        row.data.sum=[]
        for(let j=0;j<row.examineItems.length;j++){
          let item =row.examineItems[j]
          if(item.data.answerSum){
            item.data.answerSum.forEach(as=>{
              let tmp=row.data.sum.find(s=>s.id === as.id)
              if(tmp){
                tmp.point +=as.point
              }else {
                row.data.sum.push(as)
              }
            })
          }
        }
        console.log(row.data.sum)
        if(row.data.sum){
          this.getTactics(row)
        }
      },
      updateExamine(row){
        this.fetch({name:"updateExamine",data:{id:row.id,data:row.data}})
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getAnswer(item,answerId){
        this.fetch({name:"getAnswer",data:{answerId}})
          .then(res=>{
            let instance = JSON.parse(res.instance.metadata)
            if(instance.type.code === '2'){
              res.data.sum=[]
              for(let i=0;i<res.answerPages.length;i++){
                let tmp=res.answerPages[i]
                let tmp2=this.makeSections(tmp)
                res.data.sum=res.data.sum.concat(tmp2)
              }
              item.data.answerSum=res.data.sum
            }
            //把answer和体检项更新保存一下
            this.updateAnswer(res)
            this.docSumExamineItem(item)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      updateAnswer(res){
        this.fetch({name:"updateAnswer",data:{answerId:res.id,data:res.data}})
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      docSumExamineItem(res){
        this.fetch({name:"docSumExamineItem",data:{id:res.id,data:res.data}})
          .then(res=>{
            console.log(res)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeSections(page){
        let tacticsArray=[]
        page.sections=JSON.parse(page.metadata)//转化成obj
        page.sections.forEach(section=>{
          if(section.answer && section.answer !== ''){//找到有答案的题目
            if(section.type==='radio'){//如果题目类型是单选，用答案去选项里找
              let tmp = section.options.find(o=>section.answer === o.text)
              if(tmp && tmp.tactics){
                tacticsArray=this.makeAnswerSum(tacticsArray,tmp)
              }
            }else if(section.type === 'checkbox'){//如果题目类型是多选，在答案里循环选项
              let newOptions = section.options.filter(option=>option.tactics && option.tactics.length>0)//过滤没有策略的选项
              newOptions.forEach(no=>{
                section.answer.forEach(a=>{
                  if(a === no.text){
                    tacticsArray=this.makeAnswerSum(tacticsArray,no)
                  }
                })
              })
            }
          }
        })
        return tacticsArray
      },
      makeAnswerSum(tacticsArray,tmp){
        let index = tacticsArray.findIndex(su=>su.id === tmp.tactics[tmp.tactics.length-1])
        if(index <0){
          tacticsArray.push({id:tmp.tactics[tmp.tactics.length-1],point: Number(tmp.point)})
        }else {
          tacticsArray[index].point += Number(tmp.point)
        }
        return tacticsArray
      },
      createReportBtn(row){
        console.log(row.data)
        //如果有分数，就把分数存到报告。data里
        this.selModules=[]
        this.currExamine=row
        //获取一下体检用户的信息
        this.getUser(row.userId)
        this.fetch({name:"getReportModuleList"})
          .then(res=>{
            this.showDialog=true
            this.moduleList=res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      confirmCreateBtn(){
        //把顺序整一下再创建报告
        this.selModules = this.comparArray(this.selModules)
        this.createReportByExamine({reportModuleIds:this.selModules})
      },
      comparArray(a){
        let compare = function (x, y) {//比较函数
          if (x< y) {
            return -1;
          } else if (x > y) {
            return 1;
          } else {
            return 0;
          }
        }
        return a.sort(compare)
      },
      editReportBtn(row){
        console.log(row)
        //编辑报告，直接跳到浏览页面
        this.$message({
          type: 'success',
          message: '跳转页面……'
        })
        this.$router.push('/report/report-lookthrough/'+row.data.reportId)
      },
      createReportByExamine(reportModuleIds){
        this.fetch({name:"createReportByExamine",
          data:{examineId:this.currExamine.id,title:this.currExamine.data.userName+' - 体质报告',reportModuleIds,data:{sum:this.currExamine.data.sum}}})
          .then(res=>{//创建报告成功，跳转
            this.$router.push('/report/report-lookthrough/'+res.id)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      timeFormatter(date){
        return DateFormat.format(date)
      },
      lookThroughReport(scope){
        console.log('查看报告')
      },
      lookThroughFraction(row){
        console.log(row)
      },
    }
  }
</script>

<style scoped>

</style>
